﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace SDT.CodeSystem.Data
{
    /// <summary>
    /// Written by SinhNT
    /// </summary>
    internal static class Repository
    {
        internal static List<ICity> LoadCities()
        {
            var db = new DbDataContext();

            var l = new List<ICity>();

            try
            {
                var rows = db.sp_ad_cities_select_all().ToList();
                foreach (var r in rows)
                    l.Add(new City(CityCodes.FromString(r.AreaCode), CityCodes.FromString(r.Code), r.Priority, r.Name, r.nItems));
            }
            catch { throw; }
            finally { db.Dispose(); }

            return l;
        }

        internal static IList<IDistrict> LoadDistricts(ICity city)
        {
            var db = new DbDataContext();

            var l = new List<IDistrict>();

            try
            {
                var rows = db.sp_ad_districts_select_by_city_code(city.CodeAsString).ToList();
                foreach (var r in rows)
                    l.Add(new District(city, r.ID, r.Name, r.ShortName, r.nItems));
            }
            catch { throw; }
            finally { db.Dispose(); }

            return l;
        }

        internal static ICity LoadCity(int distId)
        {
            var db = new DbDataContext();
            try
            {
                var r = db.sp_ad_cities_select_by_district((short)distId).First();
                if(r != null)
                    return City.GetByCode(CityCodes.FromString(r.Code));
                return null;
            }
            catch { throw; }
            finally { db.Dispose(); }
        }
    }
}